<template>
    <add-button :max="5" :length="props.modelValue?.length" @click="handleAddSpeechcraft">
        添加一条话术
    </add-button>
    <div class="speechcraft-list-form">
        <div class="speechcraft-content">
            <div class="speechcraft-list">
                <div v-for="(item, index) in props.modelValue" :key="index" class="speechcraft-list-item">
                    <div class="speechcraft-item-title">
                        <span>话术{{ index + 1 }}</span>
                        <el-button v-if="props.modelValue.length > 1" link type="primary"
                            @click="handleRemoveSpeechCraft(index)">删除</el-button>
                    </div>
                    <material-content id="staffMaterialContent" ref="staffMaterialContentRef"
                        :re-key="`staffWelcome-${index}`" :input-content-tabs="inputContentTabs"
                        :show-material-tabs="showMaterialTabs" v-model:input-content-data="item.text"
                        :material-content-data="item.attachments" :placeholder="'请输入'" @change="changeMaterial" />
                </div>
            </div>
        </div>
        <div class="affix-phone">
            <el-affix :offset="180">
                <div class="affix-phone-wrap">
                    <phone-preview :scale="0.9" :data="props.modelValue[currentIndex]" :is-group-chat="isGroupType"
                        class="speechcraft-preview" />
                    <div v-if="props.modelValue.length > 1" class="change-button">
                        <div :class="{ disabled: currentIndex <= 0 }" @click="changePhonePreviewIndex('up')">
                            <el-icon><ArrowUp /></el-icon>
                        </div>
                        <div :class="{ disabled: currentIndex >= props.modelValue.length - 1 }" @click="changePhonePreviewIndex('down')">
                            <el-icon><ArrowDown /></el-icon>
                        </div>
                    </div>
                </div>
            </el-affix>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRoute } from "vue-router";
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import materialContent from '@renderer/components/win/materialContent/index.vue';
import phonePreview from '@renderer/components/win/phonePreview/welcomePhonePreview/materialPreview/index.vue';

import AddButton from '../add-button.vue';

const route = useRoute();
const props = defineProps({
    modelValue: {
        type: Array,
        require: true,
    }
});

const emit = defineEmits(["update:modelValue"]);

/**
 * 页面是否是新建群聊规则
 */
const isGroupType = computed(() => {
    return route.query.type === 'groupChat'
})

/* ----------------------------欢迎语配置-start---------------------------- */
// 添加员工ref实例化
const staffMaterialContentRef = ref();
/**
 * @description 配置添加员工后推送欢迎语输入框选项
 * 1: 选择文本，2:表情，5: 插入员工姓名，6:插入客户昵称
 */
const inputContentTabs = computed(() => {
    if (isGroupType.value) {
        return [2, 9, 5, 3]
    }
    return [2, 8, 5, 3];
})
/**
 * @description 欢迎语素材类型
 * 1: 图片, 2: 视频, 3: 链接, 4: 音频, 5: 文件, 6: 抽奖， 7: 电商， 8: 也是电商？？？, 9: 收集表,10 公众号, 11: 小程序
 */
const showMaterialTabs = ref<Array<string>>(['1', '2', '5', '3', '11']);

/* ----------------------------欢迎语配置-end---------------------------- */

/* ----------------------------欢迎语内容-start---------------------------- */

/**
 * 新增一条话术
 */
const handleAddSpeechcraft = () => {
    emit('update:modelValue', [
        ...(props.modelValue || []),
        {
            id: 0, // 话术组件ID, 为 空0时，表示新增
            text: '',
            attachments: []
        }
    ])
};


/**
 * 删除话术
 */
const handleRemoveSpeechCraft = (index: number) => {
    props.modelValue.splice(index, 1);
}

/**
 * 添加员工推送欢迎语更改内容时回调，实时变更v-model的值
 */
const changeMaterial = (val: any) => {
    val.welcome_info.welcome_friend_id =
        val.welcome_info.welcome_friend_id || formParams.staff_welcome.welcome_friend_id;
    formParams.staff_welcome = val.welcome_info;
};
/* ----------------------------欢迎语内容-end---------------------------- */

/* ----------------------------欢迎语样机切换-start---------------------------- */
const currentIndex = ref(0)
const setScrollCurrentPhone = (scrollTop: number) => {
    const speechcraftContent = document.querySelector('.speechcraft-content .speechcraft-list')

    // 获取主视图的高度，用来计算欢迎语的样机到达的位置是否处于一个合适的区域
    const clientHeight = document.querySelector('.el-scrollbar.main-scrollbar').clientHeight
    // 以黄金比例0.618为基准值
    const viewTop = clientHeight * 0.618

    // 临界值判断，是否还未滚动到话术的位置
    const contentTop = speechcraftContent.getBoundingClientRect().top
    // 如果是还未到达判断的距离，则一直展示第一条
    if (contentTop >= viewTop) {
        return currentIndex.value = 0
    }

    const speechcraftList = speechcraftContent.querySelectorAll('.speechcraft-list-item')

    // 拿到到达位置的元素的索引的上一条。
    let scrollIndex = Array.from(speechcraftList).findIndex(speechcraftItem => {
        const top = speechcraftItem.getBoundingClientRect().top
        return top >= viewTop
    })

    // 如果没有找到到达位置的元素，则展示最后一条
    if (scrollIndex === -1) {
        scrollIndex = speechcraftList.length
    }

    currentIndex.value = Math.max(0, scrollIndex - 1)
}

const changePhonePreviewIndex = (changeType: 'up' | 'down') => {
    if (changeType === 'up') {
        currentIndex.value = Math.max(0, currentIndex.value - 1)
    } else {
        currentIndex.value = Math.min(props.modelValue.length - 1, currentIndex.value + 1)
    }


    // 滚动至dom位置
    const speechcraftContent = document.querySelector('.speechcraft-content .speechcraft-list')
    const speechcraftList = speechcraftContent.querySelectorAll('.speechcraft-list-item')
    
    const element = speechcraftList[currentIndex.value]
    if (!element) {
        return;
    }
    element.scrollIntoView({ behavior: 'auto', block: 'center', inline: 'center' });
};
/* ----------------------------欢迎语样机切换-end---------------------------- */

defineExpose({
    setScrollCurrentPhone
})
</script>

<style lang="scss" scoped>
.speechcraft-list-form {
    display: flex;
    flex-wrap: wrap;
    position: relative;
    :deep(.button-tooltip-trigger) {
        flex: 1;
    }

    .speechcraft-content {
        position: relative;
        display: flex;
        justify-content: space-between;
        &::after {
            position: absolute;
            top: -30px;
            right: 0;
            content: "";
            border-right: 1px dashed #ccc;
            height: calc(100% + 286px);
        }
    }

    .speechcraft-list {
        min-width: 760px;
        flex: 1;
        margin-top: 12px;
    }

    .speechcraft-list-item {
        min-width: 200px;
        max-width: 600px;
        margin-top: 12px;
        padding: 16px;
        border-radius: 8px;
        // background-color: #fbfbfb;
        box-shadow: 0px 0px 1px 1px rgba(0, 0, 0, 0.06);
    }

    .speechcraft-item-title {
        font-size: 14px;
        color: #333;
        font-weight: 600;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 8px;
    }

    .affix-phone {
        position: relative;
        flex: 1;
        margin-top: -63px;

        .el-affix {
            position: absolute;
            left: 80px;
            top: 0px;
        }

        .affix-phone-wrap {
            display: flex;
            align-items: center;
            :deep(.activity-phone-preview-wrap) {
                flex: 0 0 320px;
            }
        }
    }
}

.change-button {
    width: 40px;
    height: 80px;
    user-select: none;
    text-align: center;
    border-radius: 2px;
    background-color: #ffffff;
    box-shadow: 0px 2px 8px 0px #e5e5e5;

    line-height: 40px;

    >div {
        width: 40px;
        height: 40px;

        cursor: pointer;

        &.disabled {
            cursor: not-allowed;

            background-color: var(--el-disabled-bg-color);
        }
    }

    img {
        width: 16px;
        height: 16px;
    }
}
</style>